package admin.common.config;

import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;

import java.time.format.DateTimeFormatter;

/**
 *
 * @author zgb
 * @className JacksonConfig
 * @date 2024/1/12
 * @description TODO
 */
public class JacksonConfig {
    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public JacksonConfig() {
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        return (builder) -> {
            builder.simpleDateFormat(DATE_TIME_FORMAT);
            builder.deserializers(new JsonDeserializer[]{new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT))});
            builder.deserializers(new JsonDeserializer[]{new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT))});
            /*builder.deserializers(new StdScalarDeserializer<String>(String.class) {
                @Override
                public String deserialize(JsonParser jsonParser, DeserializationContext ctx)
                        throws IOException {
                    // 重点在这儿:如果为空白则返回null
                    String value = jsonParser.getValueAsString();
                    if (value == null || "".equals(value.trim())) {
                        return null;
                    }
                    return value;
                }
            });*/
            builder.serializers(new JsonSerializer[]{new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT))});
            builder.serializers(new JsonSerializer[]{new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT))});
            builder.serializerByType(Long.class, ToStringSerializer.instance).serializerByType(Long.TYPE, ToStringSerializer.instance);
        };
    }

}
